from PyQt5.QtCore import QThread, pyqtSignal
from office import word
from qfluentwidgets import InfoBar
from traceback import format_exc
from ..base import WordFrameBase


class WordToPdfThread(QThread):
    error = pyqtSignal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.open_file = None
        self.save_file = None

    def run(self):
        try:
            word.docx2pdf(self.open_file, self.save_file)
        except Exception as e:
            self.error.emit(format_exc())

    def set_value(self, open_file, save_file):
        self.open_file = open_file
        self.save_file = save_file


class WordToPdfFrame(WordFrameBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setTitle('Word 转 PDF')
        self.setToolTipTitle('Word转Pdf')
        self.setToolTipContent('正在进行word转pdf，请稍后...')

        self.runThread = WordToPdfThread(self)
        self.runThread.started.connect(self.stateToolTip.show)

        def thread_error(content):
            InfoBar.error('错误', content, parent=self)

        self.runThread.error.connect(thread_error)

        def finished_thread():
            self.stateToolTip.hide()
            InfoBar.success('提示', '文件转换完毕', duration=3000, parent=self)

        self.runThread.finished.connect(finished_thread)
        self.startButton.clicked.connect(self.startThread)

    def startThread(self):
        openFile = self.openFileFrame.lineEditText()
        saveFile = self.saveFileFrame.lineEditText()
        if openFile == '' or saveFile == '':
            InfoBar.warning('警告', '请选择路径信息', parent=self)
            return
        self.runThread.set_value(openFile, saveFile)
        self.runThread.start()
